<?php
/**
 * 邮件账户表
 * Created on 2022/4/25 14:56
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 * @author 管昌虎
 */

namespace GuanChanghu\Library\Models;

use Illuminate\Support\Collection;

/**
 * @author 管昌虎
 * Class EmailAccount
 * @tag encryption free
 * @package GuanChanghu\Library\Models
 * Created on 2022/4/25 14:58
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
class EmailAccount extends \GuanChanghu\Models\Model
{
    /**
     * 数值精度处理
     *
     * @var string[]
     */
    protected $casts = [
        'host' => 'string',
        'port' => 'string',
        'username' => 'string',
        'password' => 'string',
        'encryption' => 'string',
        'is_enabled' => 'int',
        'today_num' => 'int',
        'daily_limit' => 'int',
    ];

    /**
     * @param Collection $form
     * @return static
     */
    public static function upsert(Collection $form): static
    {
        if ($form->has('id') && $form->get('id')) {
            // 修改
            $id = $form->pull('id');

            if ($form->has('password') && !$form->get('password')) {
                $form->pull('password');
            }

            $data = static::getById($id);

            $data->changes($form->all());
        } else {
            // 添加
            $data = static::initialize($form->all())->changes();
        }

        return $data;
    }
}
